<?php
/**
 * Created by PhpStorm.
 * User: 聪
 * Date: 2019/4/14
 * Time: 14:31
 */

namespace app;

use think\Request;
use traits\controller\Jump;
use think\Validate as Valid;

class Validate
{
    use Jump;

    public function run(Request $request)
    {
        $controller = $request->controller();
        $action     = $request->action();
        $ret        = include $request->module() . '/rules/' . $controller . '.php';
        if ($ret) {
            $methods = get_class_methods($controller);
            if (isset($methods) && in_array($action, $methods)) {
                $this->doValidate($request->param(), $controller::$action(), 'zh');
            }
        }

    }

    public function doValidate(array $data, array $rule, string $lang)
    {
        $validate = Valid::make($rule['rule']);
        if (false === $validate->check($data)) {
            $this->result([], 500, $rule['msg'][$lang][$this->getKey($validate->getError())], 'json');
        }
    }

    public function getKey($errMsg = '')
    {
        $key = '';
        for ($i = 0; $i <= strlen($errMsg); $i++) {
            if (isset($errMsg[$i])) {
                if($errMsg[$i] == '_'){
                    $key .= $errMsg[$i];
                    continue;
                }
                $str = ord($errMsg[$i]);
                if ($str > 96 && $str < 123) {
                    $key .= $errMsg[$i];
                };
            }

        }
        return $key;
    }


}